package com.example.wechat.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.wechat.utils.SHA1;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "微信消息处理接口")
@RestController
@RequestMapping("/api/wechat/message")
public class MessageController {
    private static final String token = "test";

    @GetMapping
    @ApiOperation("微信验证服务器可通性的方法，本接口无需测试")
    public String verifyToken(HttpServletRequest request){
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        if (this.check(signature,timestamp,nonce)) {
            return echostr;
        }
        return echostr;
    }

    /**
     * 微信验证服务器可通性的辅助验证方法
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    private boolean check(String signature,String timestamp,String nonce){
        String[] str = new String[]{token,timestamp,nonce};
        Arrays.sort(str);
        StringBuffer buffer = new StringBuffer();
        for (String s : str) {
            buffer.append(s);
        }
//        String temp = SHA1.encode(buffer.toString());
        return signature.equals(SHA1.encode(buffer.toString()));
    }


    @PostMapping
    @ApiOperation("接收微信服务器发来的消息并做出反应接口")
    public String receiveMessage(HttpServletRequest request) throws Exception {
        WxMpXmlMessage wxMpXmlMessage = WxMpXmlMessage.fromXml(request.getInputStream());
        System.out.println(JSONObject.toJSONString(wxMpXmlMessage));
        return "success";
    }

    /**
     * 编写方法，获取request中的流，使用SAXReader辅助类处理xml格式流，将获取的节点存入map中，返回这个map
     */
    private Map<String,String> parseXml(HttpServletRequest request) throws Exception {
        Map<String,String> map = new HashMap<>();
        Document document = new SAXReader().read(request.getInputStream());
        List<Element> elements = document.getRootElement().elements();
        for (Element element : elements) {
            map.put(element.getName(),element.getText());
        }
        return map;
    }
}
